package com.framework.common.oss;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import org.apache.http.client.entity.InputStreamFactory;

import java.io.*;

/**
 * 腾讯对象存储表
 * 参阅材料：https://cloud.tencent.com/developer/article/1559745
 */
public class TencentCosCloudStorageService extends CloudStorageService{

    private CloudStorageConfig config;
    private COSClient cosClient;
    private String bucketName;

    public TencentCosCloudStorageService(CloudStorageConfig config) {
        this.config = config;
        init();
    }

    private void init() {

        COSCredentials cred = new BasicCOSCredentials(config.getQcloudSecretId(), config.getQcloudSecretKey());
        ClientConfig clientConfig = new ClientConfig(new Region(config.getQcloudRegion()));
        this.cosClient = new COSClient(cred, clientConfig);
        this.bucketName = config.getQcloudBucketName();

    }

    @Override
    public CloudUploadResponse upload(byte[] data, String path) {
        ObjectMetadata meta = new ObjectMetadata();
        meta.addUserMetadata("rawPath",path);
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, path,new ByteArrayInputStream(data),new ObjectMetadata());
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
        //etag = md5 值
        String etag = putObjectResult.getETag();
        String url = config.getQcloudDomain() + '/' + path;
        CloudUploadResponse res = new CloudUploadResponse();
        String suffix = path.substring(path.lastIndexOf(".")+1);
        res.setExt(suffix);
        res.setPath(path);
        res.setFilesize(data.length);
        res.setSource("qcloud");
        res.setUrl(url);
        return res;
    }

    @Override
    public String uploadSuffix(byte[] data, String suffix) {
        return null;
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        return null;
    }

    @Override
    public String uploadSuffix(InputStream inputStream, String suffix) {
        return null;
    }
}
